package za.org.foobar.famon.simpleui;

import za.org.foobar.famon.model.UserData;
import za.org.foobar.famon.util.ServerUtil;
import za.org.foobar.famon.webapp.UserLogic;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * A util class for the simple UI
 */
public class SimpleUiUtil {
    private static UserLogic userLogic = UserLogic.get();

    public static String getCurrentUrl(HttpServletRequest request) {
        return request.getRequestURI() + "?" + request.getQueryString();
    }

    public static int getParameterInt(HttpServletRequest request, String name, int defaultValue) {
        String value = request.getParameter(name);
        try {
            if (value != null) {
                return Integer.parseInt(ServerUtil.urlDecode(value));
            }
        } catch (NumberFormatException ignored) {
        }
        return defaultValue;
    }

    public static long getParameterLong(HttpServletRequest request, String name, long defaultValue) {
        String value = request.getParameter(name);
        try {
            if (value != null) {
                return Long.parseLong(ServerUtil.urlDecode(value));
            }
        } catch (NumberFormatException ignored) {
        }
        return defaultValue;
    }

    public static String getLoginUrl(HttpServletRequest request) {
        return getLoginUrl(getCurrentUrl(request));
    }

    public static String getLoginUrl(String destinationUrl) {
        return userLogic.createLoginUrl(destinationUrl);
    }

    public static String getLogoutUrl(HttpServletRequest request) {
        return userLogic.createLogoutUrl(getCurrentUrl(request));
    }

    public static String getLogoutUrl(String destinationUrl) {
        return userLogic.createLogoutUrl(destinationUrl);
    }

    public static String renderLoginHeader(HttpServletRequest request) {
        StringBuilder str = new StringBuilder();
        str.append("<div style=\"width:100%\"><div class=\"loginHeader\">");
        if (userLogic.isUserLoggedIn()) {
            UserData user = userLogic.getCurrentUser();
            str.append(user.getNickname());
            if (userLogic.isUserAdmin()) {
                str.append(" | <a href=\"queue.jsp\">queue</a>");
                str.append(" | <a href=\"admin.jsp\">admin</a>");
            }
            str.append(" | <a href=\"").append(getLogoutUrl(request)).append("\">logout</a>");
        } else {
            str.append("<a href=\"").append(getLoginUrl(request)).append("\">login</a>");
        }
        str.append("</div></div>");
        return str.toString();
    }

    public static boolean handleSecurityException(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return handleSecurityException(request, response, null);
    }

    public static boolean handleSecurityException(HttpServletRequest request, HttpServletResponse response,
                                               StringBuilder error) throws IOException {
        String s = "You do not have permission to view the selected item";
        if (!userLogic.isUserLoggedIn()) {
            String url = getLoginUrl(request);
            response.sendRedirect(url);
            return true;
        } else if (error != null) {
            addError(error, s);
            return false;
        } else {
            redirectError(response, s);
            return true;
        }
    }

    public static StringBuilder addError(StringBuilder b, String text) {
        b.append("<div class=\"error\">").append(text).append("</div>");
        return b;
    }

    public static void redirectError(HttpServletResponse response, String text) throws IOException {
        String s = null;
        try {
            s = URLEncoder.encode(text, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            s = "Unknown error";
        }
        response.sendRedirect("error.jsp?error=" + s);
    }

    public static String toString(boolean b) {
        return b ? "Yes" : "No";
    }

    public static String toString(String value) {
        return value != null ? value : "(none)";
    }
}
